﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Wicresoft.SMS.Common;
using Wicresoft.SMS.Data;

namespace Wicresoft.SMS.Web.Controllers
{
    /// <summary>
    /// TODO: add some comments here
    /// </summary>
    public class AddressController : CustomBaseController
    {
        //
        // GET: /Address/
       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
        public ActionResult Index(AddressSendModle Model)
        {
            if (Model.page == 0)
                Model.page = 1;
            if (Model.key == null)
                Model.key = "";
            WebConfigProvider configProvider = new WebConfigProvider();
            IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
            int max = Convert.ToInt32(configProvider.MaxshowInHistory);
            //得到当前用户
            IUserService us = new UserService(configProvider);
            int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
            Model.Infos = dataAccess.GetNumberByUser(userid,Model.page,max,Model.key);
            Model.maxpages = dataAccess.GetPageCount(userid,max,Model.key);
            Model.IsChangeUrl = true;
            return View(Model);
        }

        [HttpPost]
        [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
        public ActionResult AddAddress(string name, string number,int id)
        {
            WebConfigProvider configProvider = new WebConfigProvider();
            IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
            //得到当前用户
            IUserService us = new UserService(configProvider);
            int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
            if (name.Trim() == null || name.Trim() == "")
            {
                TempData["msg"] = App_GlobalResources.Resources.Controller_Address_Need_User;
                return Redirect("index");
            }
            else if (number.Trim() == "" || number.Trim() == null)
            {
                TempData["msg"] = App_GlobalResources.Resources.Controller_Address_Need_Num;
                return Redirect("index");
            }
            if (id.ToString().Length != 0 && id != 0)
            {
                bool result = dataAccess.UpdateAddress(name.Trim(), number.Trim(), id);
                if (result == true)
                {
                    TempData["msg"] = App_GlobalResources.Resources.Controller_Address_Success;
                    return Redirect("index");
                }
                else
                {
                    return Redirect("index");
                }
            }
            else
            {
                int results = dataAccess.AddAddress(name.Trim(), number.Trim(), userid);
                 if (results == 1)
                { 
                    TempData["msg"] = App_GlobalResources.Resources.SqlWeb_ContactExisted;
                }
                 else if (results == 2)
                {
                    TempData["msg"] = App_GlobalResources.Resources.Controller_Send_UnknownWrong;
                }
                 else if (results == 3)
                {
                    TempData["msg"] = App_GlobalResources.Resources.SqlWeb_Success;
                }
                else
                {
                    return Redirect("index");
                }
            }return Redirect("index");
        }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
        public ActionResult deleteAddress(int addressid,string addnumber, AddressSendModle Model) 
        {
            WebConfigProvider configProvider = new WebConfigProvider();
            IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
            if (addressid.ToString().Length != 0)
            {
                dataAccess.DeleteNumberByAddressId(addressid,addnumber);
            }
            //AddressSendModle Model = new AddressSendModle();
            if (Model.page == 0)
                Model.page = 1;
            if (Model.key == null)
                Model.key = "";
            Model.IsChangeUrl = false;
            int max = Convert.ToInt32(configProvider.MaxshowInHistory);
            //得到当前用户
            IUserService us = new UserService(configProvider);
            int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
            Model.Infos = dataAccess.GetNumberByUser(userid, Model.page, max, Model.key);
            Model.maxpages = dataAccess.GetPageCount(userid, max, Model.key);
            return View("Address_Book",Model);
        }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult deleteAddressByItem(string[] items, string todo, string name, string number, AddressSendModle Model)
       {
            WebConfigProvider configProvider = new WebConfigProvider();
            IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
            if (items != null && items.Length != 0)
            {
                foreach (var strings in items)
                {
                    var lengths = strings.LastIndexOf('+');
                    int id = Convert.ToInt32(strings.Substring(0, lengths));
                    string numbers = Convert.ToString(strings.Substring(lengths+1));
                    dataAccess.DeleteNumberByAddressId(id,numbers);
                }
            }
            // AddressSendModle Model = new AddressSendModle();
            if (Model.page == 0)
                Model.page = 1;
            if (Model.key == null)
                Model.key = "";
            Model.IsChangeUrl = false;
            int max = Convert.ToInt32(configProvider.MaxshowInHistory);
            //得到当前用户
            IUserService us = new UserService(configProvider);
            int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
            Model.Infos = dataAccess.GetNumberByUser(userid, Model.page, max, Model.key);
            Model.maxpages = dataAccess.GetPageCount(userid, max, Model.key);

            var culture1 = CultureProvider.GetCurrentCultureString();
            


            return View("Address_Book", Model);
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
        public ActionResult findByKey(AddressSendModle Model)
        {
            WebConfigProvider configProvider = new WebConfigProvider();
            IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
            //得到当前用户
            IUserService us = new UserService(configProvider);
            int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
            Model.Infos = dataAccess.GetNumberByText(Model.key,userid);
            return View("index",Model);
        }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult Group(AddressGroupModel model)
       {
           if (model.page == 0)
               model.page = 1;
           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);

           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
           int max = Convert.ToInt32(configProvider.MaxshowInHistory);
           model.IsChangeUrl = true;
           model.GroupList = dataAccess.GetGroupsByUserid(userid, model.page, max);
           model.maxpages = dataAccess.GetGroupPageCount(userid, max);
       
           return View(model);
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult CreateGroup(AddressGroupModel model)
       {
           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);

           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
           dataAccess.CreateNewGroup(userid, model.NewGroupName);

           //if (model.page == 0)
           //    model.page = 1;

           //int max = Convert.ToInt32(configProvider.MaxshowInHistory);
           //model.IsChangeUrl = false;
           //model.GroupList = dataAccess.GetGroupsByUserid(userid, model.page, max);
           //model.maxpages = dataAccess.GetGroupPageCount(userid, max);

           //return View("group", model);

           if (model.page == 1)
               return RedirectToAction("group");
           else
               return RedirectToAction("group", new { page = model.page });
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult SaveUserGroupRelation(AddressGroupModel model)
       {
           model.NewGroupName = null;
           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);

           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;

          // model.GroupList = dataAccess.GetGroupsByUserid(userid);
           dataAccess.SaveRelations(userid, model.GroupId, model.item);
           TempData["msg"] = App_GlobalResources.Resources.All_Complete;
           if(model.page==1)
               return RedirectToAction("group");
           else
               return RedirectToAction("group", new { page = model.page });
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult RemoveGroup(AddressGroupModel model)
       {
           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);

           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;

           if (model.item == null)
           {
               int[] a = { model.GroupId };
               dataAccess.RemoveGroup(userid, a);
           }
           else
           {
               dataAccess.RemoveGroup(userid, model.item);
           }

           int max = Convert.ToInt32(configProvider.MaxshowInHistory);
           model.GroupList = dataAccess.GetGroupsByUserid(userid, model.page, max);
           model.maxpages = dataAccess.GetGroupPageCount(userid, max);
           model.IsChangeUrl = false;

           return View("contactlist", model);
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public JsonResult GetContactList(AddressGroupModel model)
       {
           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);

           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
           model.ContactList = dataAccess.GetContactsByGroupID(userid, model.GroupId);
           return Json(model.ContactList, JsonRequestBehavior.AllowGet);
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult Export()
       {
           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);
           List<AddressExportInfo> array = new List<AddressExportInfo>();
           AddressExportInfo[] info = null;
       
           int i = 0;
           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;
           array = dataAccess.GetContactsForExport(userid);
           info = array.ToArray();
           int num=array.Count;
           string[,] string1 = new string[num, 3];
           foreach (AddressExportInfo item in info)
           {
               string1[i, 0] = item.Group;
               string1[i, 1] = item.Name;
               string1[i, 2] = item.Number;
               i++;
           }
           ExcelMyXls obj = new ExcelMyXls();
           string path = System.AppDomain.CurrentDomain.BaseDirectory;
          
           string FileName = obj.XlsWrite(string1, path);
           return File(path + "Content/Excels/" + FileName, "application/ms-excel", FileName);
       }

       [CustomAuthorise(Flag = AuthoriseFlag.page_addressbook)]
       public ActionResult Import(HttpPostedFileBase fileUpload, string filename)
       {
          // var reader = new StreamReader(fileUpload.InputStream);
          // StreamWriter sw = new StreamWriter(fileUpload.InputStream);
          // bool isExcel97; 
           Stream stream = fileUpload.InputStream;
           byte[] buffer = new byte[stream.Length];
           stream.Read(buffer, 0, buffer.Length);
           MemoryStream ms1 = new MemoryStream(buffer);
           MemoryStream ms2 = new MemoryStream(ms1.ToArray());

           DataTable dt;
           string[] tokens = filename.Split('.');
           if (tokens[tokens.Length - 1] == "xls")
           {
               try
               {
                   dt = ExcelMyXls.TranslateToTable(ms1, 0);
               }
               catch (Exception)
               {
                   dt = ExcelUtils.TranslateToTable(ms2, 0, true);
               }
           }
           else if (tokens[tokens.Length - 1] == "xlsx")
               dt = ExcelUtils.TranslateToTable(fileUpload.InputStream, 0, false);
           else
           {
               //err
               return RedirectToAction("index");
           }

           //dt = ExcelUtils.TranslateToTable(fileUpload.InputStream, 0, isExcel97);

           WebConfigProvider configProvider = new WebConfigProvider();
           IAddressWebDataAccess dataAccess = new sqlWebAddressDataAccess(configProvider.ConnectionString);
           IUserService us = new UserService(configProvider);
           int userid = us.GetUserItemByCIL(User.Identity.Name).UserID;

           dataAccess.ImportContact(dt, userid);

           return RedirectToAction("index");
       }
    }
}
